package net.cyue.homework.student.management.util;


import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
import net.cyue.homework.student.management.db.DBConnectionPool;
import net.cyue.homework.student.management.db.DBConnectionPoolConfiguration;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;


@WebListener
public class DB implements ServletContextListener {
    public static final DBConnectionPool POOL;
    static {
        DBConnectionPoolConfiguration configuration = new DBConnectionPoolConfiguration(
            "com.mysql.cj.jdbc.Driver",
            "jdbc:mysql://localhost:3307/sims?useSSL=false",
            "root",
            "weifei"
        );
        POOL = new DBConnectionPool(configuration);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        POOL.close();
    }

    public static String generateSQL(String sql, String[] values) {
        String[] substrings = sql.split("\\?");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < values.length; i++) {
            String str = substrings[i] + "'" + values[i] + "'";
            builder.append(str);
        }
        return builder.toString();
    }
    public static String generateSQL(String sql, List<String> values) {
        String[] substrings = sql.split("\\?");
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < values.size(); i++) {
            String str = substrings[i] + "'" + values.get(i) + "'";
            builder.append(str);
        }
        return builder.toString();
    }
}

